//
//  TestView.m
//  SpecialForText
//
//  Created by 牛的mini on 4/25/14.
//  Copyright (c) 2014 牛的mini. All rights reserved.
//

#import "HDTypesettingTextView.h"
#import <CoreText/CoreText.h>

#define Font_Size 20.0
#define Draw_Inset_Y 20.0
#define Paragraph_No_Space (-0.5)

#define Text_Width_Key @"width"
#define Text_Image_Hieght_Key @"height"
#define Text_Paragraph_Key @"pargraphdent"
#define Text_Str_Key @"str"
#define Text_Font_Key @"font"

@interface HDTypesettingTextView()
{
    //段首缩进
    CGFloat pargraphdent;
    
    //段首缩进
    CGFloat headindent;
    
    //段尾缩进
    CGFloat tailindent;
    
    //多行高
    CGFloat MutiHeight;
    
    // 最大行高
    CGFloat MaxHeight;
    
    //行距
    CGFloat linespace;
    
    //段前间隔
    CGFloat paragraphspace;
    
    //首行缩进
    CGFloat firstlineindent;
    
    //图片高度
    CGFloat imageHeight;
    CGFloat perLineHeight;
    CGFloat perWordWidth;
    CGFloat firstWidth;
    
}
@property (nonatomic, strong)  UIImageView *topImageView;
@end

@implementation HDTypesettingTextView
@synthesize touchBlock;

- (void)viewInit
{
    if (self.wordsStr == nil)
        self.wordsStr = @"当前展品无介绍内容。";
    
    headindent = 0;
    tailindent = 0;
    MutiHeight = 0;
    MaxHeight = 0;
    linespace = 0;
    
    paragraphspace = 0;
    firstlineindent = 0;
    
    if (self.font == nil)
        self.font = [UIFont fontWithName:@"Arial" size:Font_Size];
    
    perLineHeight = [self.font lineHeight];
    [self setBackgroundColor:[UIColor clearColor]];
    [self ParagraphStyle];
}

- (id)initWithWidt:(CGFloat)width topHeight:(CGFloat)height andStr:(NSString *)str
{
    self = [super init];
    if (self == [super init])
    {
        firstWidth = width-Draw_Inset_Y;
        imageHeight = height;
        
        self.wordsStr = str;
        isDrawRect = NO;
        [self viewInit];
    }
    return self;
}

- (id)initWithDic:(NSDictionary *)dic
{
    self = [super init];
    CGFloat width = [[dic valueForKey:Text_Width_Key] floatValue];
    CGFloat height = [[dic valueForKey:Text_Image_Hieght_Key] floatValue];
    pargraphdent = [[dic valueForKey:Text_Paragraph_Key] floatValue];
    NSString *str = [dic valueForKey:Text_Str_Key];
    self.font = [dic valueForKey:Text_Font_Key];
    
    if (self == [super init])
    {
        firstWidth = width-Draw_Inset_Y;
        imageHeight = height;
        
        self.wordsStr = str;
        isDrawRect = NO;
        [self viewInit];
    }
    return self;
}

//- (CGFloat)wordViewHeight
//{
//    NSMutableAttributedString * mabstring = [[NSMutableAttributedString alloc] initWithString:src];
//    long slen = [mabstring length];
//    NSLog(@"%@", mabstring);
//
//    //顶部插入图片，文字下移
//    [self myTopImageView];
//
//    NSInteger characterSpaceNumber = ceil(self.topImageView.frame.size.height/perLineHeight);
//    NSAttributedString *attriStr = [[NSAttributedString alloc] initWithString:@"\n"];
//    for (int i=0; i<characterSpaceNumber; i++)
//    {
//        [mabstring insertAttributedString:attriStr atIndex:0];
//    }
//
//    NSRange range = NSMakeRange(0, slen);
//    [mabstring addAttributes:attributes range:range];
//    CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 25, NULL);
//    [mabstring addAttribute:(id)kCTFontAttributeName value:(__bridge id)font range:range];
//
//    // 重置frame
//    CGFloat selfHeight = [self wordViewHeight:mabstring];
//    CGRect rect = self.frame;
//    self.frame = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, selfHeight);
//}

-(void)ParagraphStyle
{
    NSString *src = self.wordsStr;
    //修改windows回车换行为mac的回车换行
    src = [src stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\n"];
    
    //创建文本对齐方式
    CTTextAlignment alignment = kCTJustifiedTextAlignment;//kCTNaturalTextAlignment;
    CTParagraphStyleSetting alignmentStyle;
    alignmentStyle.spec=kCTParagraphStyleSpecifierAlignment;//指定为对齐属性
    alignmentStyle.valueSize=sizeof(alignment);
    alignmentStyle.value = &alignment;
    
    //段首缩进
    headindent = 0.0f;
    CTParagraphStyleSetting head;
    head.spec = kCTParagraphStyleSpecifierHeadIndent;
    head.value = &headindent;
    head.valueSize = sizeof(CGFloat);
    
    //段尾间距
    //pargraphdent = -15.0f; //变为全局变量
    CTParagraphStyleSetting paragraphSpace;
    paragraphSpace.spec = kCTParagraphStyleSpecifierParagraphSpacing;
    paragraphSpace.value = &headindent;
    paragraphSpace.valueSize = sizeof(CGFloat);
    
    // 段前距离
    CGFloat paragraphSpacing = -pargraphdent;
    CTParagraphStyleSetting paragraphSpaceStyle;
    paragraphSpaceStyle.spec = kCTParagraphStyleSpecifierParagraphSpacingBefore;
    paragraphSpaceStyle.valueSize = sizeof(CGFloat);
    paragraphSpaceStyle.value = &paragraphSpacing;
    
    //段尾缩进
    tailindent = 10.0f;
    CTParagraphStyleSetting tail;
    tail.spec = kCTParagraphStyleSpecifierTailIndent;
    tail.value = &tailindent;
    tail.valueSize = sizeof(CGFloat);
    
    //tab
    CTTextAlignment tabalignment = kCTJustifiedTextAlignment;
    CTTextTabRef texttab = CTTextTabCreate(tabalignment, 24, NULL);
    CTParagraphStyleSetting tab;
    tab.spec = kCTParagraphStyleSpecifierTabStops;
    tab.value = &texttab;
    tab.valueSize = sizeof(CTTextTabRef);
    
    //换行模式
    CTParagraphStyleSetting lineBreakMode;
    CTLineBreakMode lineBreak = kCTLineBreakByTruncatingMiddle;//kCTLineBreakByWordWrapping;//换行模式
    lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;
    lineBreakMode.value = &lineBreak;
    lineBreakMode.valueSize = sizeof(CTLineBreakMode);
    
    //多行高
    MutiHeight = 10.0f;
    CTParagraphStyleSetting Muti;
    Muti.spec = kCTParagraphStyleSpecifierLineHeightMultiple;
    Muti.value = &MutiHeight;
    Muti.valueSize = sizeof(CGFloat);
    
    //最大行高
    MaxHeight = 5.0f;
    CTParagraphStyleSetting Max;
    Max.spec = kCTParagraphStyleSpecifierLineHeightMultiple;
    Max.value = &MaxHeight;
    Max.valueSize = sizeof(CGFloat);
    
    //行距
    linespace = 8.0f;
    CTParagraphStyleSetting lineSpaceSetting;
    lineSpaceSetting.spec = kCTParagraphStyleSpecifierLineSpacing;
    lineSpaceSetting.value = &linespace;
    lineSpaceSetting.valueSize = sizeof(CGFloat);
    
    //段前间隔
    paragraphspace = 15.0f;
    //    if (imageHeight == Paragraph_No_Space)
    //        paragraphspace = 0.0f;
    
    CTParagraphStyleSetting paragraph;
    paragraph.spec = kCTParagraphStyleSpecifierLineSpacing;
    paragraph.value = &paragraphspace;
    paragraph.valueSize = sizeof(CGFloat);
    
    //书写方向
    CTWritingDirection wd = kCTWritingDirectionRightToLeft;
    CTParagraphStyleSetting writedic;
    writedic.spec = kCTParagraphStyleSpecifierBaseWritingDirection;
    writedic.value = &wd;
    writedic.valueSize = sizeof(CTWritingDirection);
    
    //首行缩进
    firstlineindent = perLineHeight*2-6;
    CTParagraphStyleSetting fristline;
    fristline.spec = kCTParagraphStyleSpecifierFirstLineHeadIndent;
    fristline.value = &firstlineindent;
    fristline.valueSize = sizeof(CGFloat);
    
    //组合设置
    CTParagraphStyleSetting settings[] = {
        alignmentStyle,
        fristline,
        head,
        paragraph,
        lineSpaceSetting,
        paragraphSpace,
        paragraphSpaceStyle,
        //        tail,
        ////        tab,// 有问题__
        //        lineBreakMode,
        //        Muti,
        //        Max,
        //        writedic,
        //        tailindent,
    };
    
    //通过设置项产生段落样式对象
    CTParagraphStyleRef style = CTParagraphStyleCreate(settings, 7);
    
    // build attributes
    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:(__bridge id)style forKey:(id)kCTParagraphStyleAttributeName ];
    // set attributes to attributed string
    NSMutableAttributedString * mabstring = [[NSMutableAttributedString alloc] initWithString:src];
    long slen = [mabstring length];
    //    NSLog(@"%@", mabstring);
    
    //顶部插入图片，文字下移
    //    [self myTopImageView];
    //    NSInteger characterSpaceNumber = ceil(self.topImageView.frame.size.height/perLineHeight);
    //    NSAttributedString *space = [[NSAttributedString alloc] initWithString:@"\n"];
    //    for (int i=0; i<characterSpaceNumber; i++)
    //    {
    //        [mabstring insertAttributedString:space atIndex:0];
    //    }
    
    NSRange range = NSMakeRange(0, slen);
    [mabstring addAttributes:attributes range:range];
    
    //    CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), Font_Size, NULL);
    CTFontRef font = CTFontCreateWithName((CFStringRef)self.font.fontName, Font_Size, NULL);
    [mabstring addAttribute:(id)kCTFontAttributeName value:(__bridge id)font range:range];
    
    if (_textColor == nil)
        self.textColor = [UIColor whiteColor];
    [mabstring addAttribute:NSForegroundColorAttributeName value:self.textColor range:(NSRange) {0, slen}];
    // 重置frame
    self.totalHeight = [self wordViewHeight:mabstring];
    
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)mabstring);
    CGMutablePathRef Path = CGPathCreateMutable();
    
    //坐标点在左下角
    CGPathAddRect(Path, NULL ,CGRectMake(Draw_Inset_Y/2 , Draw_Inset_Y/2 ,self.bounds.size.width-Draw_Inset_Y , self.bounds.size.height-Draw_Inset_Y));
    
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL);

    //获取当前(View)上下文以便于之后的绘画，这个是一个离屏。
    if (isDrawRect == NO)
        UIGraphicsBeginImageContext(CGSizeMake(320, 320));
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(context , CGAffineTransformIdentity);
    
    //压栈，压入图形状态栈中.每个图形上下文维护一个图形状态栈，并不是所有的当前绘画环境的图形状态的元素都被保存。图形状态中不考虑当前路径，所以不保存
    //保存现在得上下文图形状态。不管后续对context上绘制什么都不会影响真正得屏幕。
    CGContextSaveGState(context);
    // 这句代码报error，CGContextSaveGState(context);
    
    //x，y轴方向移动
    CGContextTranslateCTM(context , 0 ,self.bounds.size.height);
    
    //缩放x，y轴方向缩放，－1.0为反向1.0倍,坐标系转换,沿x轴翻转180度
    CGContextScaleCTM(context, 1.0 ,-1.0);
    CTFrameDraw(frame,context);
    CGPathRelease(Path);
    CFRelease(framesetter);
    
    if (isDrawRect == NO)
        UIGraphicsEndImageContext();
}

-(void)ParagraphStyleTest
{
    NSString *src = self.wordsStr;
    //修改windows回车换行为mac的回车换行
    src = [src stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\n"];
    //    src = [src stringByReplacingOccurrencesOfString:@" " withString:@""];
    //    src = [src stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    //创建文本对齐方式
    CTTextAlignment alignment = kCTJustifiedTextAlignment;//kCTNaturalTextAlignment;
    CTParagraphStyleSetting alignmentStyle;
    alignmentStyle.spec=kCTParagraphStyleSpecifierAlignment;//指定为对齐属性
    alignmentStyle.valueSize=sizeof(alignment);
    alignmentStyle.value = &alignment;
    
    //段首缩进
    headindent = 0.0f;
    CTParagraphStyleSetting head;
    head.spec = kCTParagraphStyleSpecifierHeadIndent;
    head.value = &headindent;
    head.valueSize = sizeof(CGFloat);
    
    //段尾间距
    //pargraphdent = -15.0f; //变为全局变量
    CTParagraphStyleSetting paragraphSpace;
    paragraphSpace.spec = kCTParagraphStyleSpecifierParagraphSpacing;
    paragraphSpace.value = &headindent;
    paragraphSpace.valueSize = sizeof(CGFloat);
    
    // 段前距离
    CGFloat paragraphSpacing = -pargraphdent;
    CTParagraphStyleSetting paragraphSpaceStyle;
    paragraphSpaceStyle.spec = kCTParagraphStyleSpecifierParagraphSpacingBefore;
    paragraphSpaceStyle.valueSize = sizeof(CGFloat);
    paragraphSpaceStyle.value = &paragraphSpacing;
    
    //段尾缩进
    tailindent = 10.0f;
    CTParagraphStyleSetting tail;
    tail.spec = kCTParagraphStyleSpecifierTailIndent;
    tail.value = &tailindent;
    tail.valueSize = sizeof(CGFloat);
    
    //tab
    CTTextAlignment tabalignment = kCTJustifiedTextAlignment;
    CTTextTabRef texttab = CTTextTabCreate(tabalignment, 24, NULL);
    CTParagraphStyleSetting tab;
    tab.spec = kCTParagraphStyleSpecifierTabStops;
    tab.value = &texttab;
    tab.valueSize = sizeof(CTTextTabRef);
    
    //换行模式
    CTParagraphStyleSetting lineBreakMode;
    CTLineBreakMode lineBreak = kCTLineBreakByTruncatingMiddle;//kCTLineBreakByWordWrapping;//换行模式
    lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;
    lineBreakMode.value = &lineBreak;
    lineBreakMode.valueSize = sizeof(CTLineBreakMode);
    
    //多行高
    MutiHeight = 10.0f;
    CTParagraphStyleSetting Muti;
    Muti.spec = kCTParagraphStyleSpecifierLineHeightMultiple;
    Muti.value = &MutiHeight;
    Muti.valueSize = sizeof(CGFloat);
    
    //最大行高
    MaxHeight = 5.0f;
    CTParagraphStyleSetting Max;
    Max.spec = kCTParagraphStyleSpecifierLineHeightMultiple;
    Max.value = &MaxHeight;
    Max.valueSize = sizeof(CGFloat);
    
    //行距
    linespace = 8.0f;
    CTParagraphStyleSetting lineSpaceSetting;
    lineSpaceSetting.spec = kCTParagraphStyleSpecifierLineSpacing;
    lineSpaceSetting.value = &linespace;
    lineSpaceSetting.valueSize = sizeof(CGFloat);
    
    //段前间隔
    paragraphspace = 15.0f;
    //    if (imageHeight == Paragraph_No_Space)
    //        paragraphspace = 0.0f;
    
    CTParagraphStyleSetting paragraph;
    paragraph.spec = kCTParagraphStyleSpecifierLineSpacing;
    paragraph.value = &paragraphspace;
    paragraph.valueSize = sizeof(CGFloat);
    
    //书写方向
    CTWritingDirection wd = kCTWritingDirectionRightToLeft;
    CTParagraphStyleSetting writedic;
    writedic.spec = kCTParagraphStyleSpecifierBaseWritingDirection;
    writedic.value = &wd;
    writedic.valueSize = sizeof(CTWritingDirection);
    
    //首行缩进
    firstlineindent = perLineHeight*2-8;
    CTParagraphStyleSetting fristline;
    fristline.spec = kCTParagraphStyleSpecifierFirstLineHeadIndent;
    fristline.value = &firstlineindent;
    fristline.valueSize = sizeof(CGFloat);
    
    //组合设置
    CTParagraphStyleSetting settings[] = {
        alignmentStyle,
        fristline,
        head,
        paragraph,
        lineSpaceSetting,
        paragraphSpace,
        paragraphSpaceStyle,
        //        tail,
        ////        tab,// 有问题__
        //        lineBreakMode,
        //        Muti,
        //        Max,
        //        writedic,
        //        tailindent,
    };
    
    //通过设置项产生段落样式对象
    CTParagraphStyleRef style = CTParagraphStyleCreate(settings, 7);
    
    // build attributes
    NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:(__bridge id)style forKey:(id)kCTParagraphStyleAttributeName ];
    // set attributes to attributed string
    NSMutableAttributedString * mabstring = [[NSMutableAttributedString alloc] initWithString:src];
    long slen = [mabstring length];
    //    NSLog(@"%@", mabstring);
    
    //顶部插入图片，文字下移
    //    [self myTopImageView];
    //    NSInteger characterSpaceNumber = ceil(self.topImageView.frame.size.height/perLineHeight);
    //    NSAttributedString *space = [[NSAttributedString alloc] initWithString:@"\n"];
    //    for (int i=0; i<characterSpaceNumber; i++)
    //    {
    //        [mabstring insertAttributedString:space atIndex:0];
    //    }
    
    NSRange range = NSMakeRange(0, slen);
    [mabstring addAttributes:attributes range:range];
    
    //    CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), Font_Size, NULL);
    CTFontRef font = CTFontCreateWithName((CFStringRef)self.font.fontName, Font_Size, NULL);
    [mabstring addAttribute:(id)kCTFontAttributeName value:(__bridge id)font range:range];
    
    if (_textColor == nil)
        self.textColor = [UIColor whiteColor];
    [mabstring addAttribute:NSForegroundColorAttributeName value:self.textColor range:(NSRange) {0, slen}];
    // 重置frame
    self.totalHeight = [self wordViewHeight:mabstring];
    
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)mabstring);
    CGMutablePathRef Path = CGPathCreateMutable();
    
    //坐标点在左下角
    CGPathAddRect(Path, NULL ,CGRectMake(Draw_Inset_Y/2 , Draw_Inset_Y/2 ,self.bounds.size.width-Draw_Inset_Y , self.bounds.size.height-Draw_Inset_Y));
    
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL);
    
    //    dispatch_queue_t serialQueue = dispatch_queue_create("com.mark.serialQueue", NULL);
    //    dispatch_async(serialQueue, ^{
    //        CGContextRef context = UIGraphicsGetCurrentContext();
    //        CGContextSetTextMatrix(context , CGAffineTransformIdentity);
    //
    //        //压栈，压入图形状态栈中.每个图形上下文维护一个图形状态栈，并不是所有的当前绘画环境的图形状态的元素都被保存。图形状态中不考虑当前路径，所以不保存
    //        //保存现在得上下文图形状态。不管后续对context上绘制什么都不会影响真正得屏幕。
    //        CGContextSaveGState(context);
    //        // 这句代码报error，CGContextSaveGState(context);
    //
    //        //x，y轴方向移动
    //        CGContextTranslateCTM(context , 0 ,self.bounds.size.height);
    //
    //        //缩放x，y轴方向缩放，－1.0为反向1.0倍,坐标系转换,沿x轴翻转180度
    //        CGContextScaleCTM(context, 1.0 ,-1.0);
    //        CTFrameDraw(frame,context);
    //        CGPathRelease(Path);
    //        CFRelease(framesetter);
    //    });
    
    //获取当前(View)上下文以便于之后的绘画，这个是一个离屏。
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(context , CGAffineTransformIdentity);
    
    //压栈，压入图形状态栈中.每个图形上下文维护一个图形状态栈，并不是所有的当前绘画环境的图形状态的元素都被保存。图形状态中不考虑当前路径，所以不保存
    //保存现在得上下文图形状态。不管后续对context上绘制什么都不会影响真正得屏幕。
    CGContextSaveGState(context);
    // 这句代码报error，CGContextSaveGState(context);
    
    //x，y轴方向移动
    CGContextTranslateCTM(context , 0 ,self.bounds.size.height);
    
    //缩放x，y轴方向缩放，－1.0为反向1.0倍,坐标系转换,沿x轴翻转180度
    CGContextScaleCTM(context, 1.0 ,-1.0);
    CTFrameDraw(frame,context);
    CGPathRelease(Path);
    CFRelease(framesetter);
}

// 计算段落数并计算行数，段落间隔+行高 = 所需绘制文本的高度
- (CGFloat)wordViewHeight:(NSMutableAttributedString*)myStr
{
    BOOL drawFlag = YES;//是否绘制
    int lineCount = 0;//行数
    CFIndex currentIndex = 0;//绘制计数
    
    CFAttributedStringRef attrString;
    attrString = (__bridge CFAttributedStringRef)myStr;
    CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString(attrString);
    
    // 计算每行绘制的str
    CGFloat YValue = firstWidth- headindent - firstlineindent;
    NSString *myTestStr = [NSString stringWithFormat:@"%@", myStr];
    while(drawFlag)
    {
        if (currentIndex > 0 && currentIndex < myStr.length)
        {
            NSString *subStr = [myTestStr substringWithRange:NSMakeRange(currentIndex -1, 1)] ;
            if ([subStr isEqualToString:@"\n"])
                YValue = firstWidth- headindent - firstlineindent;
            else
                YValue = firstWidth - headindent;
        }
        
        CFIndex lineLength = CTTypesetterSuggestLineBreak(typesetter,currentIndex,YValue);
//        NSString *testStr = [self.wordsStr substringWithRange:NSMakeRange(currentIndex, lineLength)];
//        NSLog(@"test str is:%@",testStr);
        
        if(currentIndex + lineLength >= [myStr length]){
            //  NSLog(@"lineLength is:%li", lineLength);
            //  NSLog(@"lineLength is:%li", currentIndex + lineLength);
            lineCount++;
            drawFlag = NO;
        }
        lineCount++;
        currentIndex += lineLength;
    }
    
    //    NSLog(@"_______________ The Total line is %i", lineCount);
    //    UIFont *fontTemp = [UIFont fontWithName:@"Arial" size:Font_Size];
    //    UIFont *fontTemp = [UIFont fontWithName:@"Georgia" size:Font_Size];
    CGFloat lineHeight = [_font lineHeight];
    NSInteger languageKind = [[HDDeclare sharedDeclare] languageIndex];
    if (languageKind == 1 )
        lineHeight += (linespace+0.5);
    else if (languageKind == 3)
        lineHeight += (linespace+1.5);
//        lineHeight += (linespace+0.2);
    else
        lineHeight += (linespace-1.2);
    
    
    // 计算段落数
    NSUInteger cnt = 0, length = [self.wordsStr length];
    NSRange range = NSMakeRange(0, length); // 段落统计没有问题---
    while(range.location != NSNotFound)
    {
        range = [self.wordsStr rangeOfString: @"\n" options:0 range:range];
        if(range.location != NSNotFound)
        {
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            cnt++;
        }
    }
    CGFloat paraDent = -(CGFloat)cnt*(pargraphdent+8.0);

    return lineHeight*(CGFloat)lineCount+imageHeight+paraDent+Draw_Inset_Y;
}


- (void)myTopImageView
{
    //    if (self.imagePath != nil)
    //    {
    //        UIImage *image = [UIImage imageNamed:self.imagePath];
    //        if (image == nil)
    //            return;
    //
    //        CGFloat XRatio = image.size.width/self.frame.size.width;
    //        CGFloat YRatio = image.size.height/self.frame.size.height;
    //        CGFloat imageRation = MIN(XRatio, YRatio);
    //        if (self.topImageView != nil)
    //        {
    //            self.topImageView.image = nil;
    //            [self.topImageView removeFromSuperview];
    //            self.topImageView = nil;
    //        }
    //        _topImageView = [[UIImageView alloc] initWithImage:image];
    //        CGRect rect = _topImageView.frame;
    //        [_topImageView setFrame:CGRectMake(rect.origin.x, rect.origin.y, firstWidth, rect.size.height+200)];
    ////        [_topImageView setFrame:CGRectMake(0, 0, image.size.width/imageRation, image.size.height/imageRation)];
    //        imageHeight = _topImageView.frame.size.height;
    //        [self addSubview:_topImageView];
    //
    //        UITapGestureRecognizer *myTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapAction:)];
    //        [self.topImageView addGestureRecognizer:myTap];
    //    }
}

- (void)myTapAction:(UITapGestureRecognizer *)sender
{
    if (self.bigImagePath != nil)
        touchBlock(self.bigImagePath);
}

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    isDrawRect = YES;
    [self ParagraphStyle];
}

- (void)dealloc
{
    self.textColor = nil;
    self.wordsStr = nil;
    self.imagePath = nil;
    self.bigImagePath = nil;
    self.font = nil;
    self.touchBlock = nil;
}

@end
